3 * Service for looking up page revisions.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * Attribution notice: when this file was created, much of its content was taken
21 * from the Revision.php file as present in release 1.30. Refer to the history
22 * of that file for original authorship.
27 namespace MediaWiki\Storage
;
30 use CommentStoreComment
;
33 use DBAccessObjectUtils
;
36 use InvalidArgumentException
;
39 use MediaWiki\Linker\LinkTarget
;
40 use MediaWiki\User\UserIdentity
;
41 use MediaWiki\User\UserIdentityValue
;
44 use MWUnknownContentModelException
;
50 use Wikimedia\Assert\Assert
;
51 use Wikimedia\Rdbms\Database
;
52 use Wikimedia\Rdbms\DBConnRef
;
53 use Wikimedia\Rdbms\IDatabase
;
54 use Wikimedia\Rdbms\LoadBalancer
;
57 * Service for looking up page revisions.
61 * @note This was written to act as a drop-in replacement for the corresponding
62 * static methods in Revision.
64 class RevisionStore
implements IDBAccessObject
, RevisionFactory
, RevisionLookup
{
79 private $contentHandlerUseDB = true;
84 private $loadBalancer;
92 * @todo $blobStore should be allowed to be any BlobStore!
94 * @param LoadBalancer $loadBalancer
95 * @param SqlBlobStore $blobStore
96 * @param WANObjectCache $cache
97 * @param bool|string $wikiId
99 public function __construct(
100 LoadBalancer
$loadBalancer,
101 SqlBlobStore
$blobStore,
102 WANObjectCache
$cache,
105 Assert
::parameterType( 'string|boolean', $wikiId, '$wikiId' );
107 $this->loadBalancer
= $loadBalancer;
108 $this->blobStore
= $blobStore;
109 $this->cache
= $cache;
110 $this->wikiId
= $wikiId;
116 public function getContentHandlerUseDB() {
117 return $this->contentHandlerUseDB
;
121 * @param bool $contentHandlerUseDB
123 public function setContentHandlerUseDB( $contentHandlerUseDB ) {
124 $this->contentHandlerUseDB
= $contentHandlerUseDB;
128 * @return LoadBalancer
130 private function getDBLoadBalancer() {
131 return $this->loadBalancer
;
135 * @param int $mode DB_MASTER or DB_REPLICA
139 private function getDBConnection( $mode ) {
140 $lb = $this->getDBLoadBalancer();
141 return $lb->getConnection( $mode, [], $this->wikiId
);
145 * @param IDatabase $connection
147 private function releaseDBConnection( IDatabase
$connection ) {
148 $lb = $this->getDBLoadBalancer();
149 $lb->reuseConnection( $connection );
153 * @param int $mode DB_MASTER or DB_REPLICA
157 private function getDBConnectionRef( $mode ) {
158 $lb = $this->getDBLoadBalancer();
159 return $lb->getConnectionRef( $mode, [], $this->wikiId
);
163 * Determines the page Title based on the available information.
165 * MCR migration note: this corresponds to Revision::getTitle
167 * @param int|null $pageId
168 * @param int|null $revId
169 * @param int $queryFlags
172 * @throws RevisionAccessException
174 private function getTitle( $pageId, $revId, $queryFlags = 0 ) {
175 if ( !$pageId && !$revId ) {
176 throw new InvalidArgumentException( '$pageId and $revId cannot both be 0 or null' );
181 // Loading by ID is best, but Title::newFromID does not support that for foreign IDs.
182 if ( $pageId !== null && $pageId > 0 && $this->wikiId
=== false ) {
183 // TODO: better foreign title handling (introduce TitleFactory)
184 $title = Title
::newFromID( $pageId, $queryFlags );
187 // rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
188 if ( !$title && $revId !== null && $revId > 0 ) {
189 list( $dbMode, $dbOptions, , ) = DBAccessObjectUtils
::getDBOptions( $queryFlags );
191 $dbr = $this->getDbConnectionRef( $dbMode );
192 // @todo: Title::getSelectFields(), or Title::getQueryInfo(), or something like that
193 $row = $dbr->selectRow(
194 [ 'revision', 'page' ],
203 [ 'rev_id' => $revId ],
206 [ 'page' => [ 'JOIN', 'page_id=rev_page' ] ]
209 // TODO: better foreign title handling (introduce TitleFactory)
210 $title = Title
::newFromRow( $row );
215 throw new RevisionAccessException(
216 "Could not determine title for page ID $pageId and revision ID $revId"
224 * @param mixed $value
225 * @param string $name
227 * @throw IncompleteRevisionException if $value is null
228 * @return mixed $value, if $value is not null
230 private function failOnNull( $value, $name ) {
231 if ( $value === null ) {
232 throw new IncompleteRevisionException(
233 "$name must not be " . var_export( $value, true ) . "!"
241 * @param mixed $value
242 * @param string $name
244 * @throw IncompleteRevisionException if $value is empty
245 * @return mixed $value, if $value is not null
247 private function failOnEmpty( $value, $name ) {
248 if ( $value === null ||
$value === 0 ||
$value === '' ) {
249 throw new IncompleteRevisionException(
250 "$name must not be " . var_export( $value, true ) . "!"
258 * Insert a new revision into the database, returning the new revision ID
259 * number on success and dies horribly on failure.
261 * MCR migration note: this replaces Revision::insertOn
263 * @param RevisionRecord $rev
264 * @param IDatabase $dbw (master connection)
266 * @throws InvalidArgumentException
267 * @return RevisionRecord the new revision record.
269 public function insertRevisionOn( RevisionRecord
$rev, IDatabase
$dbw ) {
270 // TODO: pass in a DBTransactionContext instead of a database connection.
271 $this->checkDatabaseWikiId( $dbw );
273 if ( !$rev->getSlotRoles() ) {
274 throw new InvalidArgumentException( 'At least one slot needs to be defined!' );
277 if ( $rev->getSlotRoles() !== [ 'main' ] ) {
278 throw new InvalidArgumentException( 'Only the main slot is supported for now!' );
281 // TODO: we shouldn't need an actual Title here.
282 $title = Title
::newFromLinkTarget( $rev->getPageAsLinkTarget() );
283 $pageId = $this->failOnEmpty( $rev->getPageId(), 'rev_page field' ); // check this early
285 $parentId = $rev->getParentId() === null
286 ?
$this->getPreviousRevisionId( $dbw, $rev )
287 : $rev->getParentId();
289 // Record the text (or external storage URL) to the blob store
290 $slot = $rev->getSlot( 'main', RevisionRecord
::RAW
);
292 $size = $this->failOnNull( $rev->getSize(), 'size field' );
293 $sha1 = $this->failOnEmpty( $rev->getSha1(), 'sha1 field' );
295 if ( !$slot->hasAddress() ) {
296 $content = $slot->getContent();
297 $format = $content->getDefaultFormat();
298 $model = $content->getModel();
300 $this->checkContentModel( $content, $title );
302 $data = $content->serialize( $format );
304 // Hints allow the blob store to optimize by "leaking" application level information to it.
305 // TODO: with the new MCR storage schema, we rev_id have this before storing the blobs.
306 // When we have it, add rev_id as a hint. Can be used with rev_parent_id for
307 // differential storage or compression of subsequent revisions.
309 BlobStore
::DESIGNATION_HINT
=> 'page-content', // BlobStore may be used for other things too.
310 BlobStore
::PAGE_HINT
=> $pageId,
311 BlobStore
::ROLE_HINT
=> $slot->getRole(),
312 BlobStore
::PARENT_HINT
=> $parentId,
313 BlobStore
::SHA1_HINT
=> $slot->getSha1(),
314 BlobStore
::MODEL_HINT
=> $model,
315 BlobStore
::FORMAT_HINT
=> $format,
318 $blobAddress = $this->blobStore
->storeBlob( $data, $blobHints );
320 $blobAddress = $slot->getAddress();
321 $model = $slot->getModel();
322 $format = $slot->getFormat();
325 $textId = $this->blobStore
->getTextIdFromAddress( $blobAddress );
328 throw new LogicException(
329 'Blob address not supported in 1.29 database schema: ' . $blobAddress
333 // getTextIdFromAddress() is free to insert something into the text table, so $textId
334 // may be a new value, not anything already contained in $blobAddress.
335 $blobAddress = 'tt:' . $textId;
337 $comment = $this->failOnNull( $rev->getComment( RevisionRecord
::RAW
), 'comment' );
338 $user = $this->failOnNull( $rev->getUser( RevisionRecord
::RAW
), 'user' );
339 $timestamp = $this->failOnEmpty( $rev->getTimestamp(), 'timestamp field' );
341 # Record the edit in revisions
343 'rev_page' => $pageId,
344 'rev_parent_id' => $parentId,
345 'rev_text_id' => $textId,
346 'rev_minor_edit' => $rev->isMinor() ?
1 : 0,
347 'rev_user' => $this->failOnNull( $user->getId(), 'user field' ),
348 'rev_user_text' => $this->failOnEmpty( $user->getName(), 'user_text field' ),
349 'rev_timestamp' => $dbw->timestamp( $timestamp ),
350 'rev_deleted' => $rev->getVisibility(),
355 if ( $rev->getId() !== null ) {
356 // Needed to restore revisions with their original ID
357 $row['rev_id'] = $rev->getId();
360 list( $commentFields, $commentCallback ) =
361 CommentStore
::newKey( 'rev_comment' )->insertWithTempTable( $dbw, $comment );
362 $row +
= $commentFields;
364 if ( $this->contentHandlerUseDB
) {
365 // MCR migration note: rev_content_model and rev_content_format will go away
367 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
368 $defaultFormat = ContentHandler
::getForModelID( $defaultModel )->getDefaultFormat();
370 $row['rev_content_model'] = ( $model === $defaultModel ) ?
null : $model;
371 $row['rev_content_format'] = ( $format === $defaultFormat ) ?
null : $format;
374 $dbw->insert( 'revision', $row, __METHOD__
);
376 if ( !isset( $row['rev_id'] ) ) {
377 // only if auto-increment was used
378 $row['rev_id'] = intval( $dbw->insertId() );
380 $commentCallback( $row['rev_id'] );
382 // Insert IP revision into ip_changes for use when querying for a range.
383 if ( $row['rev_user'] === 0 && IP
::isValid( $row['rev_user_text'] ) ) {
385 'ipc_rev_id' => $row['rev_id'],
386 'ipc_rev_timestamp' => $row['rev_timestamp'],
387 'ipc_hex' => IP
::toHex( $row['rev_user_text'] ),
389 $dbw->insert( 'ip_changes', $ipcRow, __METHOD__
);
392 $newSlot = SlotRecord
::newSaved( $row['rev_id'], $blobAddress, $slot );
393 $slots = new RevisionSlots( [ 'main' => $newSlot ] );
395 $user = new UserIdentityValue( intval( $row['rev_user'] ), $row['rev_user_text'] );
397 $rev = new RevisionStoreRecord(
406 $newSlot = $rev->getSlot( 'main', RevisionRecord
::RAW
);
409 Assert
::postcondition( $rev->getId() > 0, 'revision must have an ID' );
410 Assert
::postcondition( $rev->getPageId() > 0, 'revision must have a page ID' );
411 Assert
::postcondition(
412 $rev->getComment( RevisionRecord
::RAW
) !== null,
413 'revision must have a comment'
415 Assert
::postcondition(
416 $rev->getUser( RevisionRecord
::RAW
) !== null,
417 'revision must have a user'
420 Assert
::postcondition( $newSlot !== null, 'revision must have a main slot' );
421 Assert
::postcondition(
422 $newSlot->getAddress() !== null,
423 'main slot must have an addess'
426 Hooks
::run( 'RevisionRecordInserted', [ $rev ] );
432 * MCR migration note: this corresponds to Revision::checkContentModel
434 * @param Content $content
435 * @param Title $title
437 * @throws MWException
438 * @throws MWUnknownContentModelException
440 private function checkContentModel( Content
$content, Title
$title ) {
441 // Note: may return null for revisions that have not yet been inserted
443 $model = $content->getModel();
444 $format = $content->getDefaultFormat();
445 $handler = $content->getContentHandler();
449 if ( !$handler->isSupportedFormat( $format ) ) {
450 throw new MWException( "Can't use format $format with content model $model on $name" );
453 if ( !$this->contentHandlerUseDB
) {
454 // if $wgContentHandlerUseDB is not set,
455 // all revisions must use the default content model and format.
457 $defaultModel = ContentHandler
::getDefaultModelFor( $title );
458 $defaultHandler = ContentHandler
::getForModelID( $defaultModel );
459 $defaultFormat = $defaultHandler->getDefaultFormat();
461 if ( $model != $defaultModel ) {
462 throw new MWException( "Can't save non-default content model with "
463 . "\$wgContentHandlerUseDB disabled: model is $model, "
464 . "default for $name is $defaultModel"
468 if ( $format != $defaultFormat ) {
469 throw new MWException( "Can't use non-default content format with "
470 . "\$wgContentHandlerUseDB disabled: format is $format, "
471 . "default for $name is $defaultFormat"
476 if ( !$content->isValid() ) {
477 throw new MWException(
478 "New content for $name is not valid! Content model is $model"
484 * Create a new null-revision for insertion into a page's
485 * history. This will not re-save the text, but simply refer
486 * to the text from the previous version.
488 * Such revisions can for instance identify page rename
489 * operations and other such meta-modifications.
491 * MCR migration note: this replaces Revision::newNullRevision
493 * @todo Introduce newFromParentRevision(). newNullRevision can then be based on that
496 * @param IDatabase $dbw
497 * @param Title $title Title of the page to read from
498 * @param CommentStoreComment $comment RevisionRecord's summary
499 * @param bool $minor Whether the revision should be considered as minor
500 * @param User $user The user to attribute the revision to
501 * @return RevisionRecord|null RevisionRecord or null on error
503 public function newNullRevision(
506 CommentStoreComment
$comment,
510 $this->checkDatabaseWikiId( $dbw );
512 $fields = [ 'page_latest', 'page_namespace', 'page_title',
513 'rev_id', 'rev_text_id', 'rev_len', 'rev_sha1' ];
515 if ( $this->contentHandlerUseDB
) {
516 $fields[] = 'rev_content_model';
517 $fields[] = 'rev_content_format';
520 $current = $dbw->selectRow(
521 [ 'page', 'revision' ],
524 'page_id' => $title->getArticleID(),
525 'page_latest=rev_id',
528 [ 'FOR UPDATE' ] // T51581
533 'page' => $title->getArticleID(),
534 'user_text' => $user->getName(),
535 'user' => $user->getId(),
536 'comment' => $comment,
537 'minor_edit' => $minor,
538 'text_id' => $current->rev_text_id
,
539 'parent_id' => $current->page_latest
,
540 'len' => $current->rev_len
,
541 'sha1' => $current->rev_sha1
544 if ( $this->contentHandlerUseDB
) {
545 $fields['content_model'] = $current->rev_content_model
;
546 $fields['content_format'] = $current->rev_content_format
;
549 $fields['title'] = Title
::makeTitle( $current->page_namespace
, $current->page_title
);
551 $mainSlot = $this->emulateMainSlot_1_29( $fields, 0, $title );
552 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
553 $this->initializeMutableRevisionFromArray( $revision, $fields );
554 $revision->setSlot( $mainSlot );
563 * MCR migration note: this replaces Revision::isUnpatrolled
565 * @todo This is overly specific, so move or kill this method.
567 * @param RevisionRecord $rev
569 * @return int Rcid of the unpatrolled row, zero if there isn't one
571 public function getRcIdIfUnpatrolled( RevisionRecord
$rev ) {
572 $rc = $this->getRecentChange( $rev );
573 if ( $rc && $rc->getAttribute( 'rc_patrolled' ) == 0 ) {
574 return $rc->getAttribute( 'rc_id' );
581 * Get the RC object belonging to the current revision, if there's one
583 * MCR migration note: this replaces Revision::getRecentChange
585 * @todo move this somewhere else?
587 * @param RevisionRecord $rev
588 * @param int $flags (optional) $flags include:
589 * IDBAccessObject::READ_LATEST: Select the data from the master
591 * @return null|RecentChange
593 public function getRecentChange( RevisionRecord
$rev, $flags = 0 ) {
594 $dbr = $this->getDBConnection( DB_REPLICA
);
596 list( $dbType, ) = DBAccessObjectUtils
::getDBOptions( $flags );
598 $userIdentity = $rev->getUser( RevisionRecord
::RAW
);
600 if ( !$userIdentity ) {
601 // If the revision has no user identity, chances are it never went
602 // into the database, and doesn't have an RC entry.
606 // TODO: Select by rc_this_oldid alone - but as of Nov 2017, there is no index on that!
607 $rc = RecentChange
::newFromConds(
609 'rc_user_text' => $userIdentity->getName(),
610 'rc_timestamp' => $dbr->timestamp( $rev->getTimestamp() ),
611 'rc_this_oldid' => $rev->getId()
617 $this->releaseDBConnection( $dbr );
619 // XXX: cache this locally? Glue it to the RevisionRecord?
624 * Maps fields of the archive row to corresponding revision rows.
626 * @param object $archiveRow
628 * @return object a revision row object, corresponding to $archiveRow.
630 private static function mapArchiveFields( $archiveRow ) {
632 // keep with ar prefix:
635 // not the same suffix:
636 'ar_page_id' => 'rev_page',
637 'ar_rev_id' => 'rev_id',
640 'ar_text_id' => 'rev_text_id',
641 'ar_timestamp' => 'rev_timestamp',
642 'ar_user_text' => 'rev_user_text',
643 'ar_user' => 'rev_user',
644 'ar_minor_edit' => 'rev_minor_edit',
645 'ar_deleted' => 'rev_deleted',
646 'ar_len' => 'rev_len',
647 'ar_parent_id' => 'rev_parent_id',
648 'ar_sha1' => 'rev_sha1',
649 'ar_comment' => 'rev_comment',
650 'ar_comment_cid' => 'rev_comment_cid',
651 'ar_comment_id' => 'rev_comment_id',
652 'ar_comment_text' => 'rev_comment_text',
653 'ar_comment_data' => 'rev_comment_data',
654 'ar_comment_old' => 'rev_comment_old',
655 'ar_content_format' => 'rev_content_format',
656 'ar_content_model' => 'rev_content_model',
659 if ( empty( $archiveRow->ar_text_id
) ) {
660 $fieldMap['ar_text'] = 'old_text';
661 $fieldMap['ar_flags'] = 'old_flags';
664 $revRow = new stdClass();
665 foreach ( $fieldMap as $arKey => $revKey ) {
666 if ( property_exists( $archiveRow, $arKey ) ) {
667 $revRow->$revKey = $archiveRow->$arKey;
675 * Constructs a RevisionRecord for the revisions main slot, based on the MW1.29 schema.
677 * @param object|array $row Either a database row or an array
678 * @param int $queryFlags for callbacks
679 * @param Title $title
681 * @return SlotRecord The main slot, extracted from the MW 1.29 style row.
682 * @throws MWException
684 private function emulateMainSlot_1_29( $row, $queryFlags, Title
$title ) {
685 $mainSlotRow = new stdClass();
686 $mainSlotRow->role_name
= 'main';
692 if ( is_object( $row ) ) {
694 if ( !isset( $row->rev_id
) && isset( $row->ar_user
) ) {
695 $row = $this->mapArchiveFields( $row );
698 if ( isset( $row->rev_text_id
) && $row->rev_text_id
> 0 ) {
699 $mainSlotRow->cont_address
= 'tt:' . $row->rev_text_id
;
700 } elseif ( isset( $row->ar_id
) ) {
701 $mainSlotRow->cont_address
= 'ar:' . $row->ar_id
;
704 if ( isset( $row->old_text
) ) {
705 // this happens when the text-table gets joined directly, in the pre-1.30 schema
706 $blobData = isset( $row->old_text
) ?
strval( $row->old_text
) : null;
707 $blobFlags = isset( $row->old_flags
) ?
strval( $row->old_flags
) : '';
710 $mainSlotRow->slot_revision
= intval( $row->rev_id
);
712 $mainSlotRow->cont_size
= isset( $row->rev_len
) ?
intval( $row->rev_len
) : null;
713 $mainSlotRow->cont_sha1
= isset( $row->rev_sha1
) ?
strval( $row->rev_sha1
) : null;
714 $mainSlotRow->model_name
= isset( $row->rev_content_model
)
715 ?
strval( $row->rev_content_model
)
717 // XXX: in the future, we'll probably always use the default format, and drop content_format
718 $mainSlotRow->format_name
= isset( $row->rev_content_format
)
719 ?
strval( $row->rev_content_format
)
721 } elseif ( is_array( $row ) ) {
722 $mainSlotRow->slot_revision
= isset( $row['id'] ) ?
intval( $row['id'] ) : null;
724 $mainSlotRow->cont_address
= isset( $row['text_id'] )
725 ?
'tt:' . intval( $row['text_id'] )
727 $mainSlotRow->cont_size
= isset( $row['len'] ) ?
intval( $row['len'] ) : null;
728 $mainSlotRow->cont_sha1
= isset( $row['sha1'] ) ?
strval( $row['sha1'] ) : null;
730 $mainSlotRow->model_name
= isset( $row['content_model'] )
731 ?
strval( $row['content_model'] ) : null; // XXX: must be a string!
732 // XXX: in the future, we'll probably always use the default format, and drop content_format
733 $mainSlotRow->format_name
= isset( $row['content_format'] )
734 ?
strval( $row['content_format'] ) : null;
735 $blobData = isset( $row['text'] ) ?
rtrim( strval( $row['text'] ) ) : null;
736 $blobFlags = isset( $row['flags'] ) ?
trim( strval( $row['flags'] ) ) : '';
738 // if we have a Content object, override mText and mContentModel
739 if ( !empty( $row['content'] ) ) {
740 if ( !( $row['content'] instanceof Content
) ) {
741 throw new MWException( 'content field must contain a Content object.' );
744 /** @var Content $content */
745 $content = $row['content'];
746 $handler = $content->getContentHandler();
748 $mainSlotRow->model_name
= $content->getModel();
750 // XXX: in the future, we'll probably always use the default format.
751 if ( $mainSlotRow->format_name
=== null ) {
752 $mainSlotRow->format_name
= $handler->getDefaultFormat();
756 throw new MWException( 'Revision constructor passed invalid row format.' );
759 // With the old schema, the content changes with every revision.
760 // ...except for null-revisions. Would be nice if we could detect them.
761 $mainSlotRow->slot_inherited
= 0;
763 if ( $mainSlotRow->model_name
=== null ) {
764 $mainSlotRow->model_name
= function ( SlotRecord
$slot ) use ( $title ) {
765 // TODO: MCR: consider slot role in getDefaultModelFor()! Use LinkTarget!
766 // TODO: MCR: deprecate $title->getModel().
767 return ContentHandler
::getDefaultModelFor( $title );
772 $content = function ( SlotRecord
$slot )
773 use ( $blobData, $blobFlags, $queryFlags, $mainSlotRow )
775 return $this->loadSlotContent(
779 $mainSlotRow->format_name
,
785 return new SlotRecord( $mainSlotRow, $content );
789 * Loads a Content object based on a slot row.
791 * This method does not call $slot->getContent(), and may be used as a callback
792 * called by $slot->getContent().
794 * MCR migration note: this roughly corresponds to Revision::getContentInternal
796 * @param SlotRecord $slot The SlotRecord to load content for
797 * @param string|null $blobData The content blob, in the form indicated by $blobFlags
798 * @param string $blobFlags Flags indicating how $blobData needs to be processed
799 * @param string|null $blobFormat MIME type indicating how $dataBlob is encoded
800 * @param int $queryFlags
802 * @throw RevisionAccessException
805 private function loadSlotContent(
812 if ( $blobData !== null ) {
813 Assert
::parameterType( 'string', $blobData, '$blobData' );
814 Assert
::parameterType( 'string', $blobFlags, '$blobFlags' );
816 $cacheKey = $slot->hasAddress() ?
$slot->getAddress() : null;
818 $data = $this->blobStore
->expandBlob( $blobData, $blobFlags, $cacheKey );
820 if ( $data === false ) {
821 throw new RevisionAccessException(
822 "Failed to expand blob data using flags $blobFlags (key: $cacheKey)"
826 $address = $slot->getAddress();
828 $data = $this->blobStore
->getBlob( $address, $queryFlags );
829 } catch ( BlobAccessException
$e ) {
830 throw new RevisionAccessException(
831 "Failed to load data blob from $address: " . $e->getMessage(), 0, $e
836 // Unserialize content
837 $handler = ContentHandler
::getForModelID( $slot->getModel() );
839 $content = $handler->unserializeContent( $data, $blobFormat );
844 * Load a page revision from a given revision ID number.
845 * Returns null if no such revision can be found.
847 * MCR migration note: this replaces Revision::newFromId
850 * IDBAccessObject::READ_LATEST: Select the data from the master
851 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
854 * @param int $flags (optional)
855 * @return RevisionRecord|null
857 public function getRevisionById( $id, $flags = 0 ) {
858 return $this->newRevisionFromConds( [ 'rev_id' => intval( $id ) ], $flags );
862 * Load either the current, or a specified, revision
863 * that's attached to a given link target. If not attached
864 * to that link target, will return null.
866 * MCR migration note: this replaces Revision::newFromTitle
869 * IDBAccessObject::READ_LATEST: Select the data from the master
870 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
872 * @param LinkTarget $linkTarget
873 * @param int $revId (optional)
874 * @param int $flags Bitfield (optional)
875 * @return RevisionRecord|null
877 public function getRevisionByTitle( LinkTarget
$linkTarget, $revId = 0, $flags = 0 ) {
879 'page_namespace' => $linkTarget->getNamespace(),
880 'page_title' => $linkTarget->getDBkey()
883 // Use the specified revision ID.
884 // Note that we use newRevisionFromConds here because we want to retry
885 // and fall back to master if the page is not found on a replica.
886 // Since the caller supplied a revision ID, we are pretty sure the revision is
887 // supposed to exist, so we should try hard to find it.
888 $conds['rev_id'] = $revId;
889 return $this->newRevisionFromConds( $conds, $flags );
891 // Use a join to get the latest revision.
892 // Note that we don't use newRevisionFromConds here because we don't want to retry
893 // and fall back to master. The assumption is that we only want to force the fallback
894 // if we are quite sure the revision exists because the caller supplied a revision ID.
895 // If the page isn't found at all on a replica, it probably simply does not exist.
896 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
898 $conds[] = 'rev_id=page_latest';
899 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
901 $this->releaseDBConnection( $db );
907 * Load either the current, or a specified, revision
908 * that's attached to a given page ID.
909 * Returns null if no such revision can be found.
911 * MCR migration note: this replaces Revision::newFromPageId
914 * IDBAccessObject::READ_LATEST: Select the data from the master (since 1.20)
915 * IDBAccessObject::READ_LOCKING : Select & lock the data from the master
918 * @param int $revId (optional)
919 * @param int $flags Bitfield (optional)
920 * @return RevisionRecord|null
922 public function getRevisionByPageId( $pageId, $revId = 0, $flags = 0 ) {
923 $conds = [ 'page_id' => $pageId ];
925 // Use the specified revision ID.
926 // Note that we use newRevisionFromConds here because we want to retry
927 // and fall back to master if the page is not found on a replica.
928 // Since the caller supplied a revision ID, we are pretty sure the revision is
929 // supposed to exist, so we should try hard to find it.
930 $conds['rev_id'] = $revId;
931 return $this->newRevisionFromConds( $conds, $flags );
933 // Use a join to get the latest revision.
934 // Note that we don't use newRevisionFromConds here because we don't want to retry
935 // and fall back to master. The assumption is that we only want to force the fallback
936 // if we are quite sure the revision exists because the caller supplied a revision ID.
937 // If the page isn't found at all on a replica, it probably simply does not exist.
938 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
940 $conds[] = 'rev_id=page_latest';
941 $rev = $this->loadRevisionFromConds( $db, $conds, $flags );
943 $this->releaseDBConnection( $db );
949 * Load the revision for the given title with the given timestamp.
950 * WARNING: Timestamps may in some circumstances not be unique,
951 * so this isn't the best key to use.
953 * MCR migration note: this replaces Revision::loadFromTimestamp
955 * @param Title $title
956 * @param string $timestamp
957 * @return RevisionRecord|null
959 public function getRevisionByTimestamp( $title, $timestamp ) {
960 return $this->newRevisionFromConds(
962 'rev_timestamp' => $timestamp,
963 'page_namespace' => $title->getNamespace(),
964 'page_title' => $title->getDBkey()
972 * Make a fake revision object from an archive table row. This is queried
973 * for permissions or even inserted (as in Special:Undelete)
975 * MCR migration note: this replaces Revision::newFromArchiveRow
978 * @param int $queryFlags
979 * @param Title|null $title
980 * @param array $overrides associative array with fields of $row to override. This may be
981 * used e.g. to force the parent revision ID or page ID. Keys in the array are fields
982 * names from the archive table without the 'ar_' prefix, i.e. use 'parent_id' to
983 * override ar_parent_id.
985 * @return RevisionRecord
986 * @throws MWException
988 public function newRevisionFromArchiveRow(
992 array $overrides = []
994 Assert
::parameterType( 'object', $row, '$row' );
996 // check second argument, since Revision::newFromArchiveRow had $overrides in that spot.
997 Assert
::parameterType( 'integer', $queryFlags, '$queryFlags' );
999 if ( !$title && isset( $overrides['title'] ) ) {
1000 if ( !( $overrides['title'] instanceof Title
) ) {
1001 throw new MWException( 'title field override must contain a Title object.' );
1004 $title = $overrides['title'];
1007 if ( !isset( $title ) ) {
1008 if ( isset( $row->ar_namespace
) && isset( $row->ar_title
) ) {
1009 $title = Title
::makeTitle( $row->ar_namespace
, $row->ar_title
);
1011 throw new InvalidArgumentException(
1012 'A Title or ar_namespace and ar_title must be given'
1017 foreach ( $overrides as $key => $value ) {
1019 $row->$field = $value;
1022 $user = $this->getUserIdentityFromRowObject( $row, 'ar_' );
1024 $comment = CommentStore
::newKey( 'ar_comment' )
1025 // Legacy because $row may have come from self::selectFields()
1026 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), $row, true );
1028 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1029 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1031 return new RevisionArchiveRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1035 * @param object $row
1036 * @param string $prefix Field prefix, such as 'rev_' or 'ar_'.
1038 * @return UserIdentityValue
1040 private function getUserIdentityFromRowObject( $row, $prefix = 'rev_' ) {
1041 $idField = "{$prefix}user";
1042 $nameField = "{$prefix}user_text";
1044 $userId = intval( $row->$idField );
1046 if ( isset( $row->user_name
) ) {
1047 $userName = $row->user_name
;
1048 } elseif ( isset( $row->$nameField ) ) {
1049 $userName = $row->$nameField;
1051 $userName = User
::whoIs( $userId );
1054 if ( $userName === false ) {
1055 wfWarn( __METHOD__
. ': Cannot determine user name for user ID ' . $userId );
1059 return new UserIdentityValue( $userId, $userName );
1063 * @see RevisionFactory::newRevisionFromRow_1_29
1065 * MCR migration note: this replaces Revision::newFromRow
1067 * @param object $row
1068 * @param int $queryFlags
1069 * @param Title|null $title
1071 * @return RevisionRecord
1072 * @throws MWException
1073 * @throws RevisionAccessException
1075 private function newRevisionFromRow_1_29( $row, $queryFlags = 0, Title
$title = null ) {
1076 Assert
::parameterType( 'object', $row, '$row' );
1079 $pageId = isset( $row->rev_page
) ?
$row->rev_page
: 0; // XXX: also check page_id?
1080 $revId = isset( $row->rev_id
) ?
$row->rev_id
: 0;
1082 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1085 if ( !isset( $row->page_latest
) ) {
1086 $row->page_latest
= $title->getLatestRevID();
1087 if ( $row->page_latest
=== 0 && $title->exists() ) {
1088 wfWarn( 'Encountered title object in limbo: ID ' . $title->getArticleID() );
1092 $user = $this->getUserIdentityFromRowObject( $row );
1094 $comment = CommentStore
::newKey( 'rev_comment' )
1095 // Legacy because $row may have come from self::selectFields()
1096 ->getCommentLegacy( $this->getDBConnection( DB_REPLICA
), $row, true );
1098 $mainSlot = $this->emulateMainSlot_1_29( $row, $queryFlags, $title );
1099 $slots = new RevisionSlots( [ 'main' => $mainSlot ] );
1101 return new RevisionStoreRecord( $title, $user, $comment, $row, $slots, $this->wikiId
);
1105 * @see RevisionFactory::newRevisionFromRow
1107 * MCR migration note: this replaces Revision::newFromRow
1109 * @param object $row
1110 * @param int $queryFlags
1111 * @param Title|null $title
1113 * @return RevisionRecord
1115 public function newRevisionFromRow( $row, $queryFlags = 0, Title
$title = null ) {
1116 return $this->newRevisionFromRow_1_29( $row, $queryFlags, $title );
1120 * Constructs a new MutableRevisionRecord based on the given associative array following
1121 * the MW1.29 convention for the Revision constructor.
1123 * MCR migration note: this replaces Revision::newFromRow
1125 * @param array $fields
1126 * @param int $queryFlags
1127 * @param Title|null $title
1129 * @return MutableRevisionRecord
1130 * @throws MWException
1131 * @throws RevisionAccessException
1133 public function newMutableRevisionFromArray(
1138 if ( !$title && isset( $fields['title'] ) ) {
1139 if ( !( $fields['title'] instanceof Title
) ) {
1140 throw new MWException( 'title field must contain a Title object.' );
1143 $title = $fields['title'];
1147 $pageId = isset( $fields['page'] ) ?
$fields['page'] : 0;
1148 $revId = isset( $fields['id'] ) ?
$fields['id'] : 0;
1150 $title = $this->getTitle( $pageId, $revId, $queryFlags );
1153 if ( !isset( $fields['page'] ) ) {
1154 $fields['page'] = $title->getArticleID( $queryFlags );
1157 // if we have a content object, use it to set the model and type
1158 if ( !empty( $fields['content'] ) ) {
1159 if ( !( $fields['content'] instanceof Content
) ) {
1160 throw new MWException( 'content field must contain a Content object.' );
1163 if ( !empty( $fields['text_id'] ) ) {
1164 throw new MWException(
1165 "Text already stored in external store (id {$fields['text_id']}), " .
1166 "can't serialize content object"
1171 // Replaces old lazy loading logic in Revision::getUserText.
1172 if ( !isset( $fields['user_text'] ) && isset( $fields['user'] ) ) {
1173 if ( $fields['user'] instanceof UserIdentity
) {
1174 /** @var User $user */
1175 $user = $fields['user'];
1176 $fields['user_text'] = $user->getName();
1177 $fields['user'] = $user->getId();
1179 // TODO: wrap this in a callback to make it lazy again.
1180 $name = $fields['user'] === 0 ?
false : User
::whoIs( $fields['user'] );
1182 if ( $name === false ) {
1183 throw new MWException(
1184 'user_text not given, and unknown user ID ' . $fields['user']
1188 $fields['user_text'] = $name;
1193 isset( $fields['comment'] )
1194 && !( $fields['comment'] instanceof CommentStoreComment
)
1196 $commentData = isset( $fields['comment_data'] ) ?
$fields['comment_data'] : null;
1198 if ( $fields['comment'] instanceof Message
) {
1199 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1204 $commentText = trim( strval( $fields['comment'] ) );
1205 $fields['comment'] = CommentStoreComment
::newUnsavedComment(
1212 $mainSlot = $this->emulateMainSlot_1_29( $fields, $queryFlags, $title );
1214 $revision = new MutableRevisionRecord( $title, $this->wikiId
);
1215 $this->initializeMutableRevisionFromArray( $revision, $fields );
1216 $revision->setSlot( $mainSlot );
1222 * @param MutableRevisionRecord $record
1223 * @param array $fields
1225 private function initializeMutableRevisionFromArray(
1226 MutableRevisionRecord
$record,
1229 /** @var UserIdentity $user */
1232 if ( isset( $fields['user'] ) && ( $fields['user'] instanceof UserIdentity
) ) {
1233 $user = $fields['user'];
1234 } elseif ( isset( $fields['user'] ) && isset( $fields['user_text'] ) ) {
1235 $user = new UserIdentityValue( intval( $fields['user'] ), $fields['user_text'] );
1236 } elseif ( isset( $fields['user'] ) ) {
1237 $user = User
::newFromId( intval( $fields['user'] ) );
1238 } elseif ( isset( $fields['user_text'] ) ) {
1239 $user = User
::newFromName( $fields['user_text'] );
1241 // User::newFromName will return false for IP addresses (and invalid names)
1242 if ( $user == false ) {
1243 $user = new UserIdentityValue( 0, $fields['user_text'] );
1248 $record->setUser( $user );
1251 $timestamp = isset( $fields['timestamp'] )
1252 ?
strval( $fields['timestamp'] )
1253 : wfTimestampNow(); // TODO: use a callback, so we can override it for testing.
1255 $record->setTimestamp( $timestamp );
1257 if ( isset( $fields['page'] ) ) {
1258 $record->setPageId( intval( $fields['page'] ) );
1261 if ( isset( $fields['id'] ) ) {
1262 $record->setId( intval( $fields['id'] ) );
1264 if ( isset( $fields['parent_id'] ) ) {
1265 $record->setParentId( intval( $fields['parent_id'] ) );
1268 if ( isset( $fields['sha1'] ) ) {
1269 $record->setSha1( $fields['sha1'] );
1271 if ( isset( $fields['size'] ) ) {
1272 $record->setSize( intval( $fields['size'] ) );
1275 if ( isset( $fields['minor_edit'] ) ) {
1276 $record->setMinorEdit( intval( $fields['minor_edit'] ) !== 0 );
1278 if ( isset( $fields['deleted'] ) ) {
1279 $record->setVisibility( intval( $fields['deleted'] ) );
1282 if ( isset( $fields['comment'] ) ) {
1283 Assert
::parameterType(
1284 CommentStoreComment
::class,
1288 $record->setComment( $fields['comment'] );
1293 * Load a page revision from a given revision ID number.
1294 * Returns null if no such revision can be found.
1296 * MCR migration note: this corresponds to Revision::loadFromId
1298 * @note direct use is deprecated!
1299 * @todo remove when unused! there seem to be no callers of Revision::loadFromId
1301 * @param IDatabase $db
1304 * @return RevisionRecord|null
1306 public function loadRevisionFromId( IDatabase
$db, $id ) {
1307 return $this->loadRevisionFromConds( $db, [ 'rev_id' => intval( $id ) ] );
1311 * Load either the current, or a specified, revision
1312 * that's attached to a given page. If not attached
1313 * to that page, will return null.
1315 * MCR migration note: this replaces Revision::loadFromPageId
1317 * @note direct use is deprecated!
1318 * @todo remove when unused!
1320 * @param IDatabase $db
1321 * @param int $pageid
1323 * @return RevisionRecord|null
1325 public function loadRevisionFromPageId( IDatabase
$db, $pageid, $id = 0 ) {
1326 $conds = [ 'rev_page' => intval( $pageid ), 'page_id' => intval( $pageid ) ];
1328 $conds['rev_id'] = intval( $id );
1330 $conds[] = 'rev_id=page_latest';
1332 return $this->loadRevisionFromConds( $db, $conds );
1336 * Load either the current, or a specified, revision
1337 * that's attached to a given page. If not attached
1338 * to that page, will return null.
1340 * MCR migration note: this replaces Revision::loadFromTitle
1342 * @note direct use is deprecated!
1343 * @todo remove when unused!
1345 * @param IDatabase $db
1346 * @param Title $title
1349 * @return RevisionRecord|null
1351 public function loadRevisionFromTitle( IDatabase
$db, $title, $id = 0 ) {
1353 $matchId = intval( $id );
1355 $matchId = 'page_latest';
1358 return $this->loadRevisionFromConds(
1362 'page_namespace' => $title->getNamespace(),
1363 'page_title' => $title->getDBkey()
1371 * Load the revision for the given title with the given timestamp.
1372 * WARNING: Timestamps may in some circumstances not be unique,
1373 * so this isn't the best key to use.
1375 * MCR migration note: this replaces Revision::loadFromTimestamp
1377 * @note direct use is deprecated! Use getRevisionFromTimestamp instead!
1378 * @todo remove when unused!
1380 * @param IDatabase $db
1381 * @param Title $title
1382 * @param string $timestamp
1383 * @return RevisionRecord|null
1385 public function loadRevisionFromTimestamp( IDatabase
$db, $title, $timestamp ) {
1386 return $this->loadRevisionFromConds( $db,
1388 'rev_timestamp' => $db->timestamp( $timestamp ),
1389 'page_namespace' => $title->getNamespace(),
1390 'page_title' => $title->getDBkey()
1398 * Given a set of conditions, fetch a revision
1400 * This method should be used if we are pretty sure the revision exists.
1401 * Unless $flags has READ_LATEST set, this method will first try to find the revision
1402 * on a replica before hitting the master database.
1404 * MCR migration note: this corresponds to Revision::newFromConds
1406 * @param array $conditions
1407 * @param int $flags (optional)
1408 * @param Title $title
1410 * @return RevisionRecord|null
1412 private function newRevisionFromConds( $conditions, $flags = 0, Title
$title = null ) {
1413 $db = $this->getDBConnection( ( $flags & self
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
);
1414 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1415 $this->releaseDBConnection( $db );
1417 $lb = $this->getDBLoadBalancer();
1419 // Make sure new pending/committed revision are visibile later on
1420 // within web requests to certain avoid bugs like T93866 and T94407.
1422 && !( $flags & self
::READ_LATEST
)
1423 && $lb->getServerCount() > 1
1424 && $lb->hasOrMadeRecentMasterChanges()
1426 $flags = self
::READ_LATEST
;
1427 $db = $this->getDBConnection( DB_MASTER
);
1428 $rev = $this->loadRevisionFromConds( $db, $conditions, $flags, $title );
1429 $this->releaseDBConnection( $db );
1436 * Given a set of conditions, fetch a revision from
1437 * the given database connection.
1439 * MCR migration note: this corresponds to Revision::loadFromConds
1441 * @param IDatabase $db
1442 * @param array $conditions
1443 * @param int $flags (optional)
1444 * @param Title $title
1446 * @return RevisionRecord|null
1448 private function loadRevisionFromConds(
1454 $row = $this->fetchRevisionRowFromConds( $db, $conditions, $flags );
1456 $rev = $this->newRevisionFromRow( $row, $flags, $title );
1465 * Throws an exception if the given database connection does not belong to the wiki this
1466 * RevisionStore is bound to.
1468 * @param IDatabase $db
1469 * @throws MWException
1471 private function checkDatabaseWikiId( IDatabase
$db ) {
1472 $storeWiki = $this->wikiId
;
1473 $dbWiki = $db->getDomainID();
1475 if ( $dbWiki === $storeWiki ) {
1479 // XXX: we really want the default database ID...
1480 $storeWiki = $storeWiki ?
: wfWikiID();
1481 $dbWiki = $dbWiki ?
: wfWikiID();
1483 if ( $dbWiki === $storeWiki ) {
1487 // HACK: counteract encoding imposed by DatabaseDomain
1488 $storeWiki = str_replace( '?h', '-', $storeWiki );
1489 $dbWiki = str_replace( '?h', '-', $dbWiki );
1491 if ( $dbWiki === $storeWiki ) {
1495 throw new MWException( "RevisionStore for $storeWiki "
1496 . "cannot be used with a DB connection for $dbWiki" );
1500 * Given a set of conditions, return a row with the
1501 * fields necessary to build RevisionRecord objects.
1503 * MCR migration note: this corresponds to Revision::fetchFromConds
1505 * @param IDatabase $db
1506 * @param array $conditions
1507 * @param int $flags (optional)
1509 * @return object|false data row as a raw object
1511 private function fetchRevisionRowFromConds( IDatabase
$db, $conditions, $flags = 0 ) {
1512 $this->checkDatabaseWikiId( $db );
1514 $revQuery = self
::getQueryInfo( [ 'page', 'user' ] );
1516 if ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
) {
1517 $options[] = 'FOR UPDATE';
1519 return $db->selectRow(
1520 $revQuery['tables'],
1521 $revQuery['fields'],
1530 * Return the tables, fields, and join conditions to be selected to create
1531 * a new revision object.
1533 * MCR migration note: this replaces Revision::getQueryInfo
1537 * @param array $options Any combination of the following strings
1538 * - 'page': Join with the page table, and select fields to identify the page
1539 * - 'user': Join with the user table, and select the user name
1540 * - 'text': Join with the text table, and select fields to load page text
1542 * @return array With three keys:
1543 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1544 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1545 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1547 public function getQueryInfo( $options = [] ) {
1554 $ret['tables'][] = 'revision';
1555 $ret['fields'] = array_merge( $ret['fields'], [
1569 $commentQuery = CommentStore
::newKey( 'rev_comment' )->getJoin();
1570 $ret['tables'] = array_merge( $ret['tables'], $commentQuery['tables'] );
1571 $ret['fields'] = array_merge( $ret['fields'], $commentQuery['fields'] );
1572 $ret['joins'] = array_merge( $ret['joins'], $commentQuery['joins'] );
1574 if ( $this->contentHandlerUseDB
) {
1575 $ret['fields'][] = 'rev_content_format';
1576 $ret['fields'][] = 'rev_content_model';
1579 if ( in_array( 'page', $options, true ) ) {
1580 $ret['tables'][] = 'page';
1581 $ret['fields'] = array_merge( $ret['fields'], [
1589 $ret['joins']['page'] = [ 'INNER JOIN', [ 'page_id = rev_page' ] ];
1592 if ( in_array( 'user', $options, true ) ) {
1593 $ret['tables'][] = 'user';
1594 $ret['fields'] = array_merge( $ret['fields'], [
1597 $ret['joins']['user'] = [ 'LEFT JOIN', [ 'rev_user != 0', 'user_id = rev_user' ] ];
1600 if ( in_array( 'text', $options, true ) ) {
1601 $ret['tables'][] = 'text';
1602 $ret['fields'] = array_merge( $ret['fields'], [
1606 $ret['joins']['text'] = [ 'INNER JOIN', [ 'rev_text_id=old_id' ] ];
1613 * Return the tables, fields, and join conditions to be selected to create
1614 * a new archived revision object.
1616 * MCR migration note: this replaces Revision::getArchiveQueryInfo
1620 * @return array With three keys:
1621 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
1622 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
1623 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
1625 public function getArchiveQueryInfo() {
1626 $commentQuery = CommentStore
::newKey( 'ar_comment' )->getJoin();
1628 'tables' => [ 'archive' ] +
$commentQuery['tables'],
1645 ] +
$commentQuery['fields'],
1646 'joins' => $commentQuery['joins'],
1649 if ( $this->contentHandlerUseDB
) {
1650 $ret['fields'][] = 'ar_content_format';
1651 $ret['fields'][] = 'ar_content_model';
1658 * Do a batched query for the sizes of a set of revisions.
1660 * MCR migration note: this replaces Revision::getParentLengths
1662 * @param int[] $revIds
1663 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1664 * of the corresponding revision.
1666 public function getRevisionSizes( array $revIds ) {
1667 return $this->listRevisionSizes( $this->getDBConnection( DB_REPLICA
), $revIds );
1671 * Do a batched query for the sizes of a set of revisions.
1673 * MCR migration note: this replaces Revision::getParentLengths
1675 * @deprecated use RevisionStore::getRevisionSizes instead.
1677 * @param IDatabase $db
1678 * @param int[] $revIds
1679 * @return int[] associative array mapping revision IDs from $revIds to the nominal size
1680 * of the corresponding revision.
1682 public function listRevisionSizes( IDatabase
$db, array $revIds ) {
1683 $this->checkDatabaseWikiId( $db );
1687 return $revLens; // empty
1692 [ 'rev_id', 'rev_len' ],
1693 [ 'rev_id' => $revIds ],
1697 foreach ( $res as $row ) {
1698 $revLens[$row->rev_id
] = intval( $row->rev_len
);
1705 * Get previous revision for this title
1707 * MCR migration note: this replaces Revision::getPrevious
1709 * @param RevisionRecord $rev
1710 * @param Title $title if known (optional)
1712 * @return RevisionRecord|null
1714 public function getPreviousRevision( RevisionRecord
$rev, Title
$title = null ) {
1715 if ( $title === null ) {
1716 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1718 $prev = $title->getPreviousRevisionID( $rev->getId() );
1720 return $this->getRevisionByTitle( $title, $prev );
1726 * Get next revision for this title
1728 * MCR migration note: this replaces Revision::getNext
1730 * @param RevisionRecord $rev
1731 * @param Title $title if known (optional)
1733 * @return RevisionRecord|null
1735 public function getNextRevision( RevisionRecord
$rev, Title
$title = null ) {
1736 if ( $title === null ) {
1737 $title = $this->getTitle( $rev->getPageId(), $rev->getId() );
1739 $next = $title->getNextRevisionID( $rev->getId() );
1741 return $this->getRevisionByTitle( $title, $next );
1747 * Get previous revision Id for this page_id
1748 * This is used to populate rev_parent_id on save
1750 * MCR migration note: this corresponds to Revision::getPreviousRevisionId
1752 * @param IDatabase $db
1753 * @param RevisionRecord $rev
1757 private function getPreviousRevisionId( IDatabase
$db, RevisionRecord
$rev ) {
1758 $this->checkDatabaseWikiId( $db );
1760 if ( $rev->getPageId() === null ) {
1763 # Use page_latest if ID is not given
1764 if ( !$rev->getId() ) {
1765 $prevId = $db->selectField(
1766 'page', 'page_latest',
1767 [ 'page_id' => $rev->getPageId() ],
1771 $prevId = $db->selectField(
1772 'revision', 'rev_id',
1773 [ 'rev_page' => $rev->getPageId(), 'rev_id < ' . $rev->getId() ],
1775 [ 'ORDER BY' => 'rev_id DESC' ]
1778 return intval( $prevId );
1782 * Get rev_timestamp from rev_id, without loading the rest of the row
1784 * MCR migration note: this replaces Revision::getTimestampFromId
1786 * @param Title $title
1789 * @return string|bool False if not found
1791 public function getTimestampFromId( $title, $id, $flags = 0 ) {
1792 $db = $this->getDBConnection(
1793 ( $flags & IDBAccessObject
::READ_LATEST
) ? DB_MASTER
: DB_REPLICA
1796 $conds = [ 'rev_id' => $id ];
1797 $conds['rev_page'] = $title->getArticleID();
1798 $timestamp = $db->selectField( 'revision', 'rev_timestamp', $conds, __METHOD__
);
1800 $this->releaseDBConnection( $db );
1801 return ( $timestamp !== false ) ?
wfTimestamp( TS_MW
, $timestamp ) : false;
1805 * Get count of revisions per page...not very efficient
1807 * MCR migration note: this replaces Revision::countByPageId
1809 * @param IDatabase $db
1810 * @param int $id Page id
1813 public function countRevisionsByPageId( IDatabase
$db, $id ) {
1814 $this->checkDatabaseWikiId( $db );
1816 $row = $db->selectRow( 'revision',
1817 [ 'revCount' => 'COUNT(*)' ],
1818 [ 'rev_page' => $id ],
1822 return intval( $row->revCount
);
1828 * Get count of revisions per page...not very efficient
1830 * MCR migration note: this replaces Revision::countByTitle
1832 * @param IDatabase $db
1833 * @param Title $title
1836 public function countRevisionsByTitle( IDatabase
$db, $title ) {
1837 $id = $title->getArticleID();
1839 return $this->countRevisionsByPageId( $db, $id );
1845 * Check if no edits were made by other users since
1846 * the time a user started editing the page. Limit to
1847 * 50 revisions for the sake of performance.
1849 * MCR migration note: this replaces Revision::userWasLastToEdit
1851 * @deprecated since 1.31; Can possibly be removed, since the self-conflict suppression
1852 * logic in EditPage that uses this seems conceptually dubious. Revision::userWasLastToEdit
1853 * has been deprecated since 1.24.
1855 * @param IDatabase $db The Database to perform the check on.
1856 * @param int $pageId The ID of the page in question
1857 * @param int $userId The ID of the user in question
1858 * @param string $since Look at edits since this time
1860 * @return bool True if the given user was the only one to edit since the given timestamp
1862 public function userWasLastToEdit( IDatabase
$db, $pageId, $userId, $since ) {
1863 $this->checkDatabaseWikiId( $db );
1873 'rev_page' => $pageId,
1874 'rev_timestamp > ' . $db->addQuotes( $db->timestamp( $since ) )
1877 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ]
1879 foreach ( $res as $row ) {
1880 if ( $row->rev_user
!= $userId ) {
1888 * Load a revision based on a known page ID and current revision ID from the DB
1890 * This method allows for the use of caching, though accessing anything that normally
1891 * requires permission checks (aside from the text) will trigger a small DB lookup.
1893 * MCR migration note: this replaces Revision::newKnownCurrent
1895 * @param Title $title the associated page title
1896 * @param int $revId current revision of this page. Defaults to $title->getLatestRevID().
1898 * @return RevisionRecord|bool Returns false if missing
1900 public function getKnownCurrentRevision( Title
$title, $revId ) {
1901 $db = $this->getDBConnectionRef( DB_REPLICA
);
1903 $pageId = $title->getArticleID();
1910 $revId = $title->getLatestRevID();
1915 'No latest revision known for page ' . $title->getPrefixedDBkey()
1916 . ' even though it exists with page ID ' . $pageId
1921 $row = $this->cache
->getWithSetCallback(
1922 // Page/rev IDs passed in from DB to reflect history merges
1923 $this->cache
->makeGlobalKey( 'revision-row-1.29', $db->getDomainID(), $pageId, $revId ),
1924 WANObjectCache
::TTL_WEEK
,
1925 function ( $curValue, &$ttl, array &$setOpts ) use ( $db, $pageId, $revId ) {
1926 $setOpts +
= Database
::getCacheSetOptions( $db );
1929 'rev_page' => intval( $pageId ),
1930 'page_id' => intval( $pageId ),
1931 'rev_id' => intval( $revId ),
1934 $row = $this->fetchRevisionRowFromConds( $db, $conds );
1935 return $row ?
: false; // don't cache negatives
1939 // Reflect revision deletion and user renames
1941 return $this->newRevisionFromRow( $row, 0, $title );
1947 // TODO: move relevant methods from Title here, e.g. getFirstRevision, isBigDeletion, etc.